package org.mspring.platform.security.dao.impl;

import java.util.List;

import org.mspring.platform.dao.hibernate.GenericDao;
import org.mspring.platform.security.dao.TreeItemDao;
import org.mspring.platform.security.entity.TreeItem;
import org.springframework.stereotype.Repository;

/**
 *
 * @author Gao Youbo
 * @since 2014-01-11
 */
@Repository
public class TreeItemDaoImpl extends GenericDao<TreeItem, String> implements TreeItemDao {

    @Override
    public List<TreeItem> listByRole(long roleId) {
        return list("select rt.PK.treeItem from RoleTreeItem rt where rt.PK.role.id = ?", roleId);
    }

    @Override
    public void clear() {
        executeUpdate("delete from TreeItem");
    }

    @Override
    public List<TreeItem> listTreeByUser(long userId) {
        return list(
                "select roleTreeItem.PK.treeItem from RoleTreeItem roleTreeItem, UserRole userRole where roleTreeItem.PK.role.id = userRole.PK.role.id and roleTreeItem.PK.treeItem.deleted = false and (roleTreeItem.PK.treeItem.type = ? or roleTreeItem.PK.treeItem.type = ?) and userRole.PK.user.id = ? order by roleTreeItem.PK.treeItem.id",
                new Object[] { TreeItem.Type.TREE_FOLDER, TreeItem.Type.TREE_ITEM, userId });
    }

    @Override
    public List<TreeItem> listTabByUser(String parent, long userId) {
        return list(
                "select roleTreeItem.PK.treeItem from RoleTreeItem roleTreeItem, UserRole userRole where roleTreeItem.PK.role.id = userRole.PK.role.id and roleTreeItem.PK.treeItem.deleted = false and roleTreeItem.PK.treeItem.type = ? and userRole.PK.user.id = ? and roleTreeItem.PK.treeItem.parent = ? order by roleTreeItem.PK.treeItem.id",
                new Object[] { TreeItem.Type.TAB, userId, parent });
    }

    @Override
    public List<TreeItem> listOpenTabByUser(String parent, long userId) {
        return list(
                "select roleTreeItem.PK.treeItem from RoleTreeItem roleTreeItem, UserRole userRole where roleTreeItem.PK.role.id = userRole.PK.role.id and roleTreeItem.PK.treeItem.deleted = false and  roleTreeItem.PK.treeItem.type = ? and userRole.PK.user.id = ? and roleTreeItem.PK.treeItem.parent = ? and roleTreeItem.PK.treeItem.open = true order by roleTreeItem.PK.treeItem.id",
                new Object[] { TreeItem.Type.TAB, userId, parent });
    }

}
